20180417 有些網頁需要登入訊息怎麼辦
原先我們使用內部模組urllib來提取網頁資料,
當如果需要做登入請求或其他動作,
我們可以使用Request這個外部模組來取代之前的方法。 (pip3 install requests)
請求網頁的方式(method),我們主要分成get ,post 兩種。
(可使用Chorme打開網頁>檢查>network>勾選preserve log 可看到網頁式以何種method方式請求)
get : 只做網頁開啟
以google搜尋為例,可使用requests.get()來取代原本的urllib.open()
#導入模組
import requests
#找到google搜尋頁面的網址邏輯
search = {"q": "台南美食"}
r1 = requests.get('https://www.google.com.tw/search?', search)
#印出url及其下的text內容
print (r1.url)
r2 = requests.get(r1.url)
print (r2.text)
#output
#https://www.google.com.tw/search?q=%E5%8F%B0%E5%8D%97%E7%BE%8E%E9%A3%9F
#上面連結的text文字
post : 將所需資料傳去伺服器來開啟網頁
當我們遇到某些網頁,需要給特定資料去請求時,
我們會需要用到requests.post()這個方法。
以高鐵時刻表查詢的網站為例,如下。
#高鐵時刻表查詢
#導入模組
import requests
#經由Chrome的檢查原始碼追蹤network發現,查詢結果需要給以下資料做POST的方法才能開啟
#起站:台南
#終站:桃園
#日期:2018/04/17
#時間:17:00
#方式:出發
data = {
"startStation": "9c5ac6ca-ec89-48f8-aab0-41b738cb1814",
"endStation": "fbd828d8-b1da-4b06-a3bd-680cdca4d2cd",
"theDay": "2018/04/17",
"timeSelect": "17:00",
"waySelect": "DepartureInMandarin",
}
# 使用將data和對應網頁包進去,丟給request.post來抓取 (得到結果的原始碼)
res = requests.post('https://m.thsrc.com.tw/tw/TimeTable/SearchResultList', data)
print (res.text)
[同場加映]
方法很爛但不知道該怎麼做更好的BS取出所需資料
from bs4 import BeautifulSoup
soup = BeautifulSoup(res.text,features='lxml')
number = soup.find_all("a",{"class":"ui-block-a"},'<div>')
start = soup.find_all("a",{"class":"ui-block-b"},'<div>')
end = soup.find_all("a",{"class":"ui-block-c"},'<div>')
number_list=[]
start_list=[]
end_list=[]
for n in number:
number_list.append(n.text)
for s in start:
start_list.append(s.text)
for e in end:
end_list.append(e.text)
#print (number_list,'\n',start_list,'\n',end_list)
for i in range(100):
if i<len(number_list):
print ("車次:",number_list[i]," 發車:",start_list[i]," 到達:",end_list[i])
else:
pass
#output
#車次: 0666 發車: 17:13 到達: 18:36
#車次: 0846 發車: 17:41 到達: 19:18
#車次: 0670 發車: 17:48 到達: 19:09
#車次: 0672 發車: 18:13 到達: 19:36
#車次: 0850 發車: 18:41 到達: 20:18
#車次: 0676 發車: 18:48 到達: 20:09
#車次: 0678 發車: 19:13 到達: 20:36
#車次: 0854 發車: 19:41 到達: 21:18
#車次: 0684 發車: 20:13 到達: 21:36
#車次: 0858 發車: 20:41 到達: 22:18